import adminApi from '@/services/adminApi';
import {
  AppstoreOutlined,
  DeleteOutlined,
  EditOutlined,
  LeftOutlined,
  PlusOutlined,
  RightOutlined,
  UsergroupAddOutlined,
} from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProCard, ProTable } from '@ant-design/pro-components';
import { Button, Menu, message, Popconfirm, Tag, Tooltip } from 'antd';
import type { DataNode, TreeProps } from 'antd/lib/tree';
import Tree from 'antd/lib/tree';
import React, { useEffect, useRef, useState } from 'react';
import ShowRole from './components/ShowRole';
import UpdateOrg from './components/UpdateOrg';
import UpdateUser from './components/UpdateUser';

export type Member = {
  avatar: string;
  realName: string;
  nickName: string;
  email: string;
  outUserNo: string;
  phone: string;
  role: RoleType;
  permission?: string[];
};

export type RoleMapType = Record<
  string,
  {
    name: string;
    desc: string;
  }
>;

export type RoleType = 'admin' | 'operator';

const tableListDataSource: Member[] = [];

const realNames = ['马巴巴', '测试', '测试2', '测试3'];
const nickNames = ['巴巴', '测试', '测试2', '测试3'];
const emails = ['baba@antfin.com', 'test@antfin.com', 'test2@antfin.com', 'test3@antfin.com'];
const phones = ['12345678910', '10923456789', '109654446789', '109223346789'];
const permissions = [[], ['权限点名称1', '权限点名称4'], ['权限点名称1'], []];

for (let i = 0; i < 5; i += 1) {
  tableListDataSource.push({
    outUserNo: `${102047 + i}`,
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/upvrAjAPQX/Logo_Tech%252520UI.svg',
    role: i === 0 ? 'admin' : 'operator',
    realName: realNames[i % 4],
    nickName: nickNames[i % 4],
    email: emails[i % 4],
    phone: phones[i % 4],
    permission: permissions[i % 4],
  });
}

const User: React.FC = () => {
  const [updateModalVisible, handleUpdateModalVisible] = useState<number>(0);
  const [currentRow, setCurrentRow] = useState<any>({});
  const [gData, setGData] = useState<any>([]);
  const [closeTree, setCloseTree] = useState(false);
  const [selectedKeys, setselectedKeys] = useState<any>(['all']);
  const [expandAll, setExpandAll] = useState<any>([]);
  const [showUpdateUser, setShowUpdateUser] = useState<number>(0);
  const [showRole, setShowRole] = useState(false);
  const [roleid, setRoleid] = useState(0);
  const [userRow, setUserRow] = useState({});
  const ref = useRef<ActionType>();
  const onDragEnd: TreeProps['onDragEnd'] = async () => {
    console.log(gData);
    await adminApi.cwSys.AdminapiCwSysDroporg({}, gData);
    // expandedKeys 需要受控时设置
    // setExpandedKeys(info.expandedKeys)
  };
  const onDrop: TreeProps['onDrop'] = (info) => {
    // console.log(info);
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (
      data: DataNode[],
      key: React.Key,
      callback: (node: DataNode, i: number, data: DataNode[]) => void,
    ) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].key === key) {
          return callback(data[i], i, data);
        }
        if (data[i].children) {
          loop(data[i].children!, key, callback);
        }
      }
    };
    const data = [...gData];
    // Find dragObject
    let dragObj: DataNode;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else if (
      ((info.node as any).props.children || []).length > 0 && // Has children
      (info.node as any).props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
        // in previous version, we use item.children.push(dragObj) to insert the
        // item to the tail of the children
      });
    } else {
      let ar: DataNode[] = [];
      let i: number;
      loop(data, dropKey, (_item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i!, 0, dragObj!);
      } else {
        ar.splice(i! + 1, 0, dragObj!);
      }
    }
    // console.log(data);
    setGData(data);
  };
  const [allrole, setallrole] = useState({});
  const getallroel = async () => {
    const res: any = await adminApi.cwSys.AdminapiCwSysGetallrole({});
    const obj = {};
    for (const m of res.data) {
      obj[m?.value] = m?.label;
    }
    setallrole(obj);
  };
  useEffect(() => {
    getallroel();
  }, []);
  const columns: ProColumns<Member>[] = [
    {
      dataIndex: 'username',
      title: '账号',
      fixed: true,
    },
    {
      dataIndex: 'email',
      title: '邮箱',
    },
    {
      dataIndex: 'mobile',
      title: '手机号',
    },
    {
      dataIndex: 'cw_roles',
      title: '角色',
      valueType: 'select',
      search: false,
      filters: true,
      valueEnum: allrole,
      render: (_, record: any) => (
        <>
          {record.admin ? (
            <Tag color="red">系统管理员</Tag>
          ) : (
            record?.cw_roles.map((o: any) => (
              <Tag
                key={o.value}
                onClick={() => {
                  console.log(o.value);
                  setShowRole(true);
                  setRoleid(o.value);
                }}
              >
                {o.label}
              </Tag>
            ))
          )}
        </>
      ),
    },
    {
      dataIndex: 'cw_org',
      title: '组织',
      search: false,
      render: (_, record: any) => {
        return record?.cw_org?.name ? record?.cw_org?.name : '-';
      },
    },
    {
      disable: true,
      title: '状态',
      dataIndex: 'state',
      filters: true,
      valueType: 'select',
      search: false,
      width: 80,
      valueEnum: {
        false: {
          text: '禁用',
          status: 'Error',
        },
        true: {
          text: '启用',
          status: 'Success',
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'x',
      valueType: 'option',
      fixed: 'right',
      width: 110,
      render: (_, record: any, index, action) => {
        return [
          <a
            key="edit"
            onClick={() => {
              setShowUpdateUser(2);
              setUserRow(record);
            }}
          >
            编辑
          </a>,
          record?.id !== 1 && (
            <Popconfirm
              key="popconfirm"
              title={`确认删除吗?`}
              okText="是"
              cancelText="否"
              onConfirm={async () => {
                await adminApi.cwSys.AdminapiCwSysDeluser({ id: record?.id });
                action?.reload();
                message.success('删除成功');
              }}
            >
              <a>删除</a>
            </Popconfirm>
          ),
        ];
      },
    },
  ];
  //获取组织
  const orgList = async () => {
    const res: any = await adminApi.cwSys.AdminapiCwSysOrglist({});
    setGData(res.data?.tree);
    setExpandAll(res.data?.expandAll);
  };
  useEffect(() => {
    orgList();
  }, []);
  return (
    <PageContainer
      extra={[
        <Button
          key="addUser"
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setShowUpdateUser(1)}
        >
          添加用户
        </Button>,
      ]}
    >
      <ProCard gutter={16} ghost>
        {closeTree ? (
          <Button icon={<RightOutlined />} onClick={() => setCloseTree(false)} />
        ) : (
          <ProCard
            title="组织架构"
            actions={[
              JSON.stringify(currentRow) !== '{}' ? (
                <Tooltip placement="bottom" title="删除组织架构" key="delOrg">
                  <Popconfirm
                    title={`确认删除吗?`}
                    okText="是"
                    cancelText="否"
                    onConfirm={async () => {
                      await adminApi.cwSys.AdminapiCwSysDelorg({ id: currentRow.id });
                      setselectedKeys(['all']);
                      setCurrentRow({});
                      message.success('删除成功！');
                      await orgList();
                    }}
                  >
                    <Button
                      disabled={JSON.stringify(currentRow) === '{}'}
                      danger
                      block
                      style={{ border: 'none' }}
                      icon={<DeleteOutlined />}
                    />
                  </Popconfirm>
                </Tooltip>
              ) : (
                <Tooltip placement="bottom" title="删除组织架构" key="delOrg">
                  <Button
                    disabled={JSON.stringify(currentRow) === '{}'}
                    danger
                    block
                    style={{ border: 'none' }}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              ),
              <Tooltip placement="bottom" title="编辑组织架构" key="editOrg">
                <Button
                  disabled={JSON.stringify(currentRow) === '{}'}
                  block
                  style={{ border: 'none' }}
                  icon={<EditOutlined />}
                  onClick={() => handleUpdateModalVisible(2)}
                />
              </Tooltip>,
              <Tooltip placement="bottom" title="添加组织架构" key="addOrg">
                <Button
                  block
                  style={{ border: 'none' }}
                  icon={<UsergroupAddOutlined />}
                  onClick={() => handleUpdateModalVisible(1)}
                />
              </Tooltip>,
            ]}
            headerBordered
            bodyStyle={{
              paddingRight: 0,
              paddingLeft: 0,
              paddingTop: 0,
              paddingBottom: 15,
            }}
            style={{ paddingBottom: 5 }}
            extra={
              <Button type="dashed" icon={<LeftOutlined />} onClick={() => setCloseTree(true)} />
            }
          >
            <Menu
              onClick={() => {
                setselectedKeys(['all']);
                setCurrentRow({});
              }}
              selectedKeys={selectedKeys}
              mode="inline"
              items={[{ label: '全部', key: 'all', icon: <AppstoreOutlined /> }]}
            />
            <Tree
              className="draggable-tree"
              expandedKeys={expandAll}
              draggable
              blockNode
              onDragEnd={onDragEnd}
              onDrop={onDrop}
              treeData={gData}
              height={400}
              showLine={{ showLeafIcon: false }}
              onSelect={(
                selectedKeys1,
                e: { selected: boolean; selectedNodes: any; node: any; event: any },
              ) => {
                console.log(selectedKeys1);
                setselectedKeys(selectedKeys1);
                if (e.selected) {
                  setCurrentRow(e.node);
                } else {
                  setCurrentRow({});
                }
              }}
              selectedKeys={selectedKeys}
              onExpand={(expandedKeys) => {
                console.log(expandedKeys);
                setExpandAll(expandedKeys);
              }}
            />
          </ProCard>
        )}
        <ProCard colSpan={closeTree ? 23 : 20} ghost>
          <ProTable<Member>
            actionRef={ref}
            headerTitle="成员列表"
            columns={columns}
            params={{ org_id: selectedKeys[0] }}
            request={async (params: any, sorter, filter): Promise<any> => {
              // 表单搜索项会从 params 传入，传递给后端接口。
              console.log(params, sorter, filter);
              params.sorter = sorter;
              params.filter = filter;
              return await adminApi.cwSys.AdminapiCwSysUserlist(params);
            }}
            rowKey="id"
            pagination={{
              showQuickJumper: true,
            }}
            search={{
              labelWidth: 'auto',
            }}
            scroll={{ x: 1300 }}
          />
        </ProCard>
      </ProCard>
      <UpdateOrg
        onSubmit={async (value: any) => {
          console.log(value);
          let res;
          if (updateModalVisible == 1) {
            res = await adminApi.cwSys.AdminapiCwSysAddorg({}, value);
          } else {
            res = await adminApi.cwSys.AdminapiCwSysEditorg({}, value);
          }
          if (res?.errorCode == '0') {
            handleUpdateModalVisible(0);
            message.success('操作成功！');
            await orgList();
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(0);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <UpdateUser
        onCancel={function (): void {
          setShowUpdateUser(0);
        }}
        onSubmit={async (values: API.userItem) => {
          console.log(values);
          let res;
          if (showUpdateUser == 1) {
            res = await adminApi.cwSys.AdminapiCwSysAdduser({}, values);
          } else {
            res = await adminApi.cwSys.AdminapiCwSysEdituser({}, values);
          }
          if (res?.errorCode === '0') {
            ref?.current?.reload();
            message.success('操作成功！');
            setShowUpdateUser(0);
          } else {
            message.error('操作失败！');
          }
        }}
        visible={showUpdateUser}
        values={userRow || {}}
      />
      <ShowRole id={roleid} visible={showRole} onClose={() => setShowRole(false)} />
    </PageContainer>
  );
};

export default User;
